package com.tgy.crud.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tgy.crud.common.CommonResult;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class WebErrorConfig {

    @Bean
    public DefaultErrorAttributes defaultErrorAttributes(){

        return new DefaultErrorAttributes(){

            @Override
            public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {

                Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
                Object result = webRequest.getAttribute("result", WebRequest.SCOPE_REQUEST);

                if (result != null && (result instanceof CommonResult)){

                    Map<String, Object> customErrorAttributes = new HashMap<>();
                    CommonResult commonResult = (CommonResult) result;
                    customErrorAttributes.put("status",commonResult.getCode());
                    customErrorAttributes.put("message",commonResult.getMessage());
                    Object path = errorAttributes.get("path");
                    if (path != null){
                        customErrorAttributes.put("path",path);
                    }
                    customErrorAttributes.put("data",commonResult.getData());
                    return  customErrorAttributes;
                }

                return errorAttributes;
            }
        };
    }

}
